package com.smarttest.portal.service.impl;

import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.smarttest.portal.service.ExportFileService;

@Service
public class ExportFileServiceImpl implements ExportFileService {

	@Override
	public void init(HttpServletResponse response) throws UnsupportedEncodingException {
		response.reset();
		response.setCharacterEncoding("GBK");
		response.setHeader("Content-disposition", "attachment;filename="
				+ new String("export.csv".getBytes("GBK"), "iso8859-1"));
		response.setContentType("application/oct-stream");
	}

	@Override
	public void write(String[] titleSet,JSONArray jarr, HttpServletResponse response) throws IOException {
		PrintWriter output = response.getWriter();

		for (int i = 0; i < jarr.size(); i++) {
			JSONObject itemJson = jarr.getJSONObject(i);
			for (String title:titleSet) {
				String value = StringUtils.isEmpty(itemJson.getString(title)) ? ""
						: itemJson.getString(title);
				value = value.replace(",", "，");
				output.print(value);
				output.print(",");
			}
			output.println();
		}
		output.flush();
	}

	@Override
	public void close(HttpServletResponse response) throws IOException {
		PrintWriter output = response.getWriter();
		output.close();		
	}

	@Override
	public void writeTitle(String[] titleSet, HttpServletResponse response) throws IOException {
		PrintWriter output = response.getWriter();
		for (String title:titleSet) {
			output.print(title);
			output.print(",");
		}	
		output.println();
		output.flush();
	}

	
	
}
